import {React,Fragment,useState,useEffect} from 'react';
import {Table,Button,Space,Input,Modal,Select,Form,message,Switch} from 'antd';
import { CloseOutlined, CheckOutlined,EditOutlined,DeleteOutlined} from '@ant-design/icons';
import {inject,observer} from 'mobx-react';
import './css/CustomerInfo.css';

const {Option} = Select;
// 成功提示框
const success = (value) => {
  message.success(value);
};
// 失败提示
const error = (value) => {
  message.error(value);
};
//列名 
const mapFieldToChinese = {
  id:'序号',
  productName:'商品名称',
  salesMode:'销售方式',
  priceType:'价格类型',
  productType:'商品类型',
  IntegralCoefficient:'积分系数',
  isEnable:'是否启用',

}
// 复选
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    // Column configuration not to be checked
    name: record.name,
  }),
};


function IntegralRule(props) {

    const [productType,setProductType] = useState('')
    function productTypeChange(value) {
      setProductType(value)
    }
    const [priceType,setPriceType] = useState('')
    function priceTypeChange(value) {
      setPriceType(value)
    }
    const [salesMode,setSalesMode] = useState('')
    function salesModeChange(value) {
      setSalesMode(value)
    }
   const [id,setId] = useState()//获取序号
      // 添加xiugai框状态
      const [add, setAdd] = useState(false);
      const [addEdit,setAddEdit]=useState('')//判断是添加还是修改
        // 删除提示模态框
      const [del, setDel] = useState(false);
      const [form] = Form.useForm();
      // 添加修改
      let obj = '';
      function addEditInfo(fun){
              let values = obj
              values.id = id
              values.fun = fun
              props.CustomerManagement.addEditIntegralRule(values).then((res)=>{
                if(res.code==200){
                  success(res.msg)
                }
                getList()
              }).catch((err)=>{
                  error(err.msg)
                console.log(err);
              })
      }
      //此为Modal点击确定以后的回调
      const okHandle = async () => {
        const fieldsValue = await form.validateFields();
        //fieldsValue即为表单内的值
        obj = fieldsValue;
        addEditInfo(addEdit);
        console.log(obj);
        console.log("okHandle -> fieldsValue", fieldsValue)
        form.resetFields();
      };
      // 删除
      function delInfo(){
        let values = {
          id:id
        }
        props.CustomerManagement.delIntegralRule(values).then((res)=>{
          console.log(res);
          if(res.code==200){
            success(res.msg)
          }
          getList()
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      } 
      // 查询
      function searchInfo() {
        let values = {
          productType:productType,
          priceType:priceType,
          salesMode:salesMode
        }
        props.CustomerManagement.searchIntegralRule(values).then((res)=>{
          if(res.code==200){
            console.log(res.data);
            setData(res.data)
            success(res.msg)
          }
        }).catch((err)=>{
          console.log(err);
          error(err.msg)
        })
      }
      // 获取
      function getList() {
        props.CustomerManagement.getIntegralRuleList().then((res)=>{
          let keys = Object.keys(res.data[0]);
          let cols = keys.map(item=>{
            if(item == 'salesMode'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: (val)=>{
                  if(val == 0){
                      return (
                          <span>重量</span>
                      )
                  }else if(val == 1){
                      return (
                          <span>数量</span>
                      )
                  }
              }
              }
            }
            else if(item == 'priceType'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: (val)=>{
                  if(val == 0){
                      return (
                          <span>原价</span>
                      )
                  }else if(val == 1){
                      return (
                          <span>特价</span>
                      )
                  }
              }
              }
            }
            else if(item == 'productType'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: (val)=>{
                  if(val == 1){
                      return (
                          <span>白银</span>
                      )
                  }else if(val == 2){
                      return (
                          <span>黄金</span>
                      )
                  }else if(val == 3){
                    return (
                        <span>铂金</span>
                    )
                  }else if(val == 4){
                    return (
                        <span>素金</span>
                    )
                  }else if(val == 5){
                    return (
                        <span>钻石</span>
                    )
                  }
              }
              }
            }            
            else if(item == 'isEnable'){
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center',
                render: (val)=>{
                  if(val == 0){
                      return (
                          <span>否</span>
                      )
                  }else if(val == 1){
                      return (
                          <span>是</span>
                      )
                }
              }
              }
            }
            else{
              return {
                width: 170,
                title: mapFieldToChinese[item],
                dataIndex: item,
                key: item,
                align: 'center'
              }
            }
          })
          cols.push({
            width:130,
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            align: 'center',
            fixed: 'right',
            render: ()=>{
                return(
                  <Space>
                  <Button shape="circle" type='primary' icon={<EditOutlined />} onClick={()=>{setAdd(true);setAddEdit(1)}}></Button>
                  <Button shape="circle" type='danger' icon={<DeleteOutlined />} onClick={()=>{setDel(true)}}></Button>
                </Space>
                )
            }
          })
          setColumns(cols)
          setData(res.data)
        }).catch((err)=>{
          console.log(err);
        }).finally(()=> {setLoading(false);})
      }
  // 渲染table
      const [selectionType, setSelectionType] = useState('checkbox');
      const [columns,setColumns] = useState([]);
      const [data,setData] = useState([]);
      const [loading,setLoading] = useState(false)
      useEffect(()=>{
        setLoading(true)
        getList()
      },[]);
    return (
        <Fragment>
            <Table 
            loading={loading}
            rowSelection={{
            type: selectionType,
                ...rowSelection,
            }} bordered='true' 
            title={() => {return (<Fragment>
              <h4>积分规则</h4>
              <div>
                <div>

                  <div className='select'>
                    <div>
                        <div>
                            商品类型：<Select placeholder='请选择' style={{ width: 120 }} onChange={productTypeChange}>
                                            <Option value="1">白银</Option>
                                            <Option value="2">黄金</Option>
                                            <Option value="3">铂金</Option>
                                            <Option value="4">素金</Option>
                                            <Option value="5">钻石</Option>
                                    </Select>
                        </div>
                        <div>
                            销售方式：<Select placeholder='请选择' style={{ width: 120 }} onChange={salesModeChange}>
                                            <Option value="0">重量</Option>
                                            <Option value="1">数量</Option>
                                    </Select>
                        </div>
                        <div>
                            价格类型：<Select placeholder='请选择' style={{ width: 120 }} onChange={priceTypeChange}>
                                            <Option value="0">原价</Option>
                                            <Option value="1">特价</Option>
                                    </Select>
                        </div>
                        <div>
                            <Button type='primary' onClick={searchInfo}>查询</Button>
                        </div>
                        <div>
                            <Button type='primary' onClick={getList}>重置</Button>
                        </div>
                    </div>
                    <div>
                        <Button type='primary' onClick={()=>{
                            setAdd(true)
                            setAddEdit(0)
                          }
                        }>创建积分规则</Button>
                    </div>
                  </div>
                </div>
              </div>
              </Fragment>)}} 
            onRow = {(record) => {
              return {
                onClick: () => {
                  setId(record.id)
                  }
                }
              }
            }
            columns={columns} dataSource={data} rowKey={(record) => `id${record.id}`} pagination={{ pageSize: 10 }} scroll={{ y: 400 }}></Table>
          {/* 删除提示 */}
          <Modal title="删除提示" 
            visible={del}
            okText= '确定'
            cancelText= '取消'
            onOk={() => {
              delInfo()
              setDel(false)
            }}
            onCancel={() => {setDel(false)}}
            >
              <p>你确定要删除这条信息吗</p>
            </Modal>
            {/* 添加修改框 */}
            <Modal
              title="详细信息"
              centered
              visible={add}
              okText= '确定'
              cancelText= '取消'
              onOk={() => {
                setAdd(false);
                okHandle();
              }}
              onCancel={() => {setAdd(false);}}
              width={1000}
            >
          <Form
            form={form}
            name="customerInfo"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            autoComplete="off"
          >
        <div className='addModalForm'>
                <div>
                <Form.Item
                  label="商品名称："
                  name="productName"
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="销售方式："
                  name="salesMode"
                >
                  <Select placeholder='请选择'>
                    <Option value="0">重量</Option>
                    <Option value="1">数量</Option>
                  </Select>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="价格类型："
                  name="priceType"
                >
                  <Select placeholder='请选择'>
                    <Option value="0">原价</Option>
                    <Option value="1">特价</Option>
                  </Select>
                </Form.Item>
                </div>

                <div>
                <Form.Item
                  label="商品类型："
                  name="productType"
                >
                  <Select placeholder='请选择'>
                    <Option value="1">白银</Option>
                    <Option value="2">黄金</Option>
                    <Option value="3">铂金</Option>
                    <Option value="4">素金</Option>
                    <Option value="5">钻石</Option>
                  </Select>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="积分系数："
                  name="IntegralCoefficient"
                >
                  <Input placeholder='请输入'/>
                </Form.Item>
                </div>
                <div>
                <Form.Item
                  label="是否启用："
                  name="isEnable"
                  valuePropName='checked'
                >
                    <Switch
                      checkedChildren={<CheckOutlined />}
                      unCheckedChildren={<CloseOutlined />}
                    />
                </Form.Item>
                </div>
              </div>
              </Form>
            </Modal>
        </Fragment>
    );
}

export default inject('CustomerManagement')(observer(IntegralRule))
// export default IntegralRule;